package com.g4.shoppingback.controller;


import com.g4.shoppingback.annotation.WriteLog;
import com.g4.shoppingback.common.PageVo;
import com.g4.shoppingback.common.Result;
import com.g4.shoppingback.pojo.DdUsersInfo;
import com.g4.shoppingback.service.IDdUsersInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;



@RestController
@CrossOrigin
@RequestMapping("/shoppingback/ddUsersInfo")
public class DdUsersInfoController {

    @Autowired
    private IDdUsersInfoService iDdUsersInfoService;

    /**
     * 根据id查询用户和角色
     * @param id 用户id
     * @return 单个用户信息
     */
    @GetMapping("/{id}")
    public Result selectUserById(@PathVariable Integer id){
        DdUsersInfo ddUsersInfo = iDdUsersInfoService.selectUserById(id);
        return Result.ok(ddUsersInfo);
    }

    /**
     * 根据分页信息或用户名查询用户
     * @param pageVo 封装了查询关键字和页数
     * @return 返回分页信息
     */
    @PreAuthorize("hasAnyAuthority('miShop:user:find')")
    @GetMapping
    public Result selectUserByPage(PageVo pageVo){
        PageVo pageResult = iDdUsersInfoService.selectUserByPaged(pageVo);
        return Result.ok(pageResult);
    }

    /**
     * 根据用户id删除用户
     * @param id 用户id
     * @return 返回提示
     */
    @WriteLog("删除用户")
    @PreAuthorize("hasAnyAuthority('miShop:user:delete')")
    @DeleteMapping("/{id}")
    public Result deleteUserById(@PathVariable Integer id){
        int row = iDdUsersInfoService.deleteUserById(id);
        if(row==1){
            return Result.success("删除成功!");
        }else {
            return Result.error("删除失败");
        }
    }

    /**
     * 新增用户
     * @param ddUsersInfo
     * @return 成功提示
     */
    @WriteLog("新增用户")
    @PreAuthorize("hasAnyAuthority('miShop:user:add')")
    @PostMapping
    public Result addUser(@RequestBody DdUsersInfo ddUsersInfo){
        int row = iDdUsersInfoService.addUser(ddUsersInfo);
        if(row==1){
            return Result.success("新增用户成功!");
        }else {
            return Result.error("新增用户失败!");
        }
    }

    /**
     * 校验用户名和电话是否重复
     * @param username 用户名
     * @param telephone 电话
     * @return 返回判断结果
     */
    @GetMapping("/checkNameAndPhone")
    public Result checkNameAndPhone(String username,String telephone){
        String msg = iDdUsersInfoService.checkNameAndPhone(username,telephone);
        return Result.success(msg); //msg=null验证通过,!null验证不通过
    }

    /**
     * 修改用户信息
     * @param ddUsersInfo
     * @return 返回提示
     */
    @WriteLog("修改用户")
    @PreAuthorize("hasAnyAuthority('miShop:user:update')")
    @PutMapping
    public Result updateUser(@RequestBody DdUsersInfo ddUsersInfo){
        int row = iDdUsersInfoService.updateUser(ddUsersInfo);
        if(row==1){
            return Result.success("修改用户成功!");
        }else {
            return Result.error("修改用户失败!");
        }
    }

}
